package com.changeover.service;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.changeover.dao.IUserDao;
import com.changeover.gwt.shared.model.User;
import com.changeover.gwt.shared.model.UserRole;

@Service
public class UserService implements IUserService {
    
    private static final List<String> unchangedUsernames = Arrays.asList("admin", "manager", "agent");
    
    @Autowired
    private IUserDao userDao;
    
    @Transactional(readOnly = true)
    public List<User> getAllUsers() {
        List<User> users = userDao.getAll();
        return users;
    }

    @Transactional
    public void saveUser(Integer id, String name, String passwd, String role) {
        User user;
        if (name == null || "".equals(name) || passwd == null || "".equals(passwd)) {
            throw new IllegalStateException("Username and password must be set!");
        }
        if (id != null) {
            if (! unchangedUsernames.contains(name)) {
                user = userDao.get(id);
                if (user == null) {
                    throw new IllegalStateException("No such user[id=" + id + "]!");
                }
            } else {
                throw new IllegalStateException("You cannot change or delete predefined users.");
            }
        } else {
            user = userDao.getUser(name);
            if (user != null) {
                throw new IllegalStateException("User with username [" + name + "] already exists!");
            }
            user = new User();
        }
        user.setName(name);
        user.setPasswd(passwd);
        user.addRole(new UserRole(role));
//        if (!role.equals("ROLE_AGENT")) 
//            user.addRole(new UserRole2("ROLE_AGENT"));
        userDao.saveOrUpdate(user);
        
    }

    @Transactional
    public void deleteUser(Integer id) {
        if (id != null) {
            User user = userDao.get(id);
            if (! unchangedUsernames.contains(user.getName())) {
                userDao.delete(id);
            } else {
                throw new IllegalStateException("You cannot cahange or delete predefined users.");
            }
        }
    }
}
